import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:provider/provider.dart';
import 'package:qunaimedical/components/custom_avatar.dart';
import 'package:qunaimedical/components/custom_divider.dart';
import 'package:qunaimedical/components/item_option.dart';
import 'package:qunaimedical/init/provider.dart';
import 'package:qunaimedical/models/list_response.dart';
import 'package:qunaimedical/models/map_response.dart';
import 'package:qunaimedical/models/user.dart';
import 'package:qunaimedical/network/http.dart';
import 'package:qunaimedical/pages/field_edit.dart';
import 'package:qunaimedical/utils/common_util.dart';
import 'package:qunaimedical/utils/dialog_utils.dart';
import 'package:qunaimedical/utils/log_utils.dart';
import 'package:qunaimedical/utils/sp_utils.dart';
import 'package:qunaimedical/values/urls.dart';

/// 个人信息界面
class ProfilePage extends StatefulWidget {
  static const String routeName = '/profile';

  @override
  _ProfilePageState createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {
  static String _tag = '_ProfilePageState';

  @override
  Widget build(BuildContext context) {
    User user = context.watch<StoreInfo>().user;
    return Scaffold(
      appBar: AppBar(title: Text('个人账号')),
      body: ListView(
        children: [
          CustomDivider(),
          ItemOption(
            height: 100,
            text: '头像',
            trailing: CustomAvatar(
              size: 70,
              avatarUrl: user.avatar,
              margin: EdgeInsets.only(right: 10),
            ),
            onTap: _selectAvatar,
          ),
          ItemOption(
            text: '姓名',
            secondText: user?.fullname ?? '',
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (c) => FieldEditPage(
                    type: FieldEditType.name,
                    value: user.fullname,
                  ),
                ),
              ).then((value) {
                Log.d(_tag, value);
                if (value != null) {
                  _updateName(value);
                }
              });
            },
          ),
        ],
      ),
    );
  }

  void _selectAvatar() {
    showDialog(
        context: context,
        builder: (c) {
          return SimpleDialog(
            title: Text('更换头像'),
            children: [
              SimpleDialogOption(
                child: Padding(
                  padding: const EdgeInsets.symmetric(vertical: 8.0),
                  child: Text('从相册选取'),
                ),
                onPressed: () => _selectImage(0),
              ),
              SimpleDialogOption(
                child: Padding(
                  padding: const EdgeInsets.symmetric(vertical: 8.0),
                  child: Text('使用相机拍摄'),
                ),
                onPressed: () => _selectImage(1),
              ),
            ],
          );
        });
  }

  final _picker = ImagePicker();

  /// 选中的图片
  PickedFile _image;

  void _selectImage(int index) async {
    Navigator.pop(context);
    var data = await _picker.getImage(
        source: index == 0 ? ImageSource.gallery : ImageSource.camera);
    if (data != null) {
      _image = data;
      _uploadImages();
    }
  }

  /// 图片上传
  void _uploadImages() async {
    DialogUtils.showWaitDialog(context);
    FormData formData = FormData.fromMap({});
    formData.files.addAll((await CommonUtils.files2MapEntry([_image])));
    var value = await XHttp.uploadFiles(
      Urls.UPLOAD,
      formData,
    );
    Navigator.pop(context);
    if (value != null) {
      ListResponse response = ListResponse.fromJson(value);
      if (response.code == 1) {
        _updateAvatar(response.data.first);
      }
    }
  }

  void _updateAvatar(String avatarPath) async {
    var data = await XHttp.postJson(Urls.DOCTOR_INFO_EDIT, {
      'id': SPUtils.getUser().id,
      'avatar': avatarPath,
    });
    if (data != null && mounted) {
      MapResponse response = MapResponse.fromJson(data);
      if (response.code == 1) {
        var storeInfo = context.read<StoreInfo>();
        User user = storeInfo.user;
        user.avatar = avatarPath;
        storeInfo.updateUser(user);
      }
    }
  }

  void _updateName(String name) async {
    DialogUtils.showWaitDialog(context);
    var data = await XHttp.postJson(Urls.DOCTOR_INFO_EDIT, {
      'id': SPUtils.getUser().id,
      'fullname': name,
    });
    Navigator.pop(context);
    if (data != null && mounted) {
      MapResponse response = MapResponse.fromJson(data);
      if (response.code == 1) {
        var storeInfo = context.read<StoreInfo>();
        User user = storeInfo.user;
        user.fullname = name;
        storeInfo.updateUser(user);
      }
    }
  }
}
